import {_decorator, Component, instantiate, Node, Prefab} from 'cc';
import {Constant} from '../../config/Constant';
import {Projectile} from './Projectile';
import {logUtil} from "../../framework/util/logUtil";
import {Pools} from "../../framework/entity/ao/Pools";

const {ccclass, property} = _decorator;

/**
 * 投射物发射器
 */
@ccclass('ProjectileEmitter')
export class ProjectileEmitter extends Component {

    /**
     * 投射物预制体
     */
    @property(Prefab)
    projectile: Prefab | null = null;

    /**
     * 投射物内存池
     */
    prefabPool: Pools<string, Node> = new Pools();

    //日志控制器
    log = logUtil.instance
    logLevel = "ProjectileEmitter"

    //预制体名称
    prefabName = "projectile"

    init() {
        const poolCount = 1;

        this.prefabPool.newPool(
            this.prefabName,
            (): Node => {
                let node = instantiate(this.projectile!);
                node.active = false;
                return node;
            },
            poolCount,
            (node: Node) => {
                node.removeFromParent();
            }
        );
    }

    onDestroy() {
        this.prefabPool.destroyAll();
    }

    create(): Projectile {
        this.log.log(this.logLevel, `${this.node.name}create`)
        let node = this.prefabPool.allocc(this.prefabName);
        this.node.addChild(node);
        node.active = true;
        node.once(Constant.EVENT_NAME.onProjectileDead, this.onProjectileDead, this);
        let projectile = node.getComponent(Projectile);
        return projectile;
    }

    //回收
    onProjectileDead(projectile: Projectile) {
        this.log.log(this.logLevel, `${this.node.name}onProjectileDead`)

        this.scheduleOnce(() => {
            projectile.node.active = false;
            this.prefabPool.free(this.prefabName, projectile.node);
        }, 0.1)

    }
}

